package com.qf.filter;

import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.serviceimpl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

@WebFilter(urlPatterns = "/jsp/login.jsp",dispatcherTypes = {DispatcherType.REQUEST,DispatcherType.FORWARD})
public class AutoFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {

    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        Cookie[] cookies = request.getCookies();
        if(cookies==null){
            chain.doFilter(req, resp);
        }else{
            for(Cookie cookie : cookies){
                if("autolg".equals(cookie.getName())){
                    String content = cookie.getValue();
                    if(content==null){
                        chain.doFilter(req, resp);
                    }else{
                        content = URLDecoder.decode(content);
                        String[] strings = content.split(":");
                        String username = strings[0];
                        String password = strings[1];
                        UserService us = new UserServiceImpl();
                        User user = us.loginUser(username, password);
                        if(user!=null){
                            HttpSession session = request.getSession();
                            session.setAttribute("user",user);
                            response.sendRedirect(request.getContextPath()+"/");
                        }
                    }
                }
            }
        }

        chain.doFilter(req, resp);
    }


    public void destroy() {
    }

}
